<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>动态皮肤</title>
  </head>
  <body>
    <div>
        <h2>Change Theme</h2>
        <button id="red">Red</button>
        <button id="purple">Purple</button>
        <button id="blue">Blue</button>
    </div>
    <hello-theme></hello-theme>
    <script>
      const Base = "h1 { font-style: italic; }";
      const Red = "h1 {  color: pink; }";
      const Purple = "h1 {  color: blueviolet; }";
      const Blue = "h1 {  color: skyblue; }";

      const themeMap = {
        red: Red,
        purple: Purple,
        blue: Blue,
      };

      const adoptedStyleSheetBase = new CSSStyleSheet();
      adoptedStyleSheetBase.replaceSync(Base);

      class HelloTheme extends HTMLElement {
        constructor() {
          super();
          this.attachShadow({ mode: "open" });

          this.setTheme();

          const container = document.createElement("h1");
          container.innerHTML = "Hello Theme";
          this.shadowRoot.appendChild(container);
        }

        static get observedAttributes() {
          return ["theme"];
        }
        attributeChangedCallback(name, oldVal, newVal) {
          if (name === "theme") {
            console.log(name + " 被更新 " + newVal + "(attributeChangedCallback)");

            const adoptedStyleSheetTheme = new CSSStyleSheet();
            adoptedStyleSheetTheme.replaceSync(Red);
            this.shadowRoot.adoptedStyleSheets = [
              adoptedStyleSheetBase,
              adoptedStyleSheetTheme,
            ];
          }
        }

        setTheme(theme = 'red') {
          const themeSheet = themeMap[theme];
          if (themeSheet) {
            const adoptedStyleSheetTheme = new CSSStyleSheet();
            adoptedStyleSheetTheme.replaceSync(themeSheet);
            this.shadowRoot.adoptedStyleSheets = [
              adoptedStyleSheetBase,
              adoptedStyleSheetTheme,
            ];
          }
        }
      }
      customElements.define("hello-theme", HelloTheme);

      const RedBtn = document.querySelector("#red");
      RedBtn.addEventListener("click", () => {
        console.log("点击了 Red");
        document.querySelector("hello-theme").setTheme("red");
      });

      const PurpleBtn = document.querySelector("#purple");
      PurpleBtn.addEventListener("click", () => {
        console.log("点击了 Purple");
        document.querySelector("hello-theme").setTheme("purple");
      });


      const BlueBtn = document.querySelector("#blue");
      BlueBtn.addEventListener("click", () => {
        console.log("点击了 Blue");
        document.querySelector("hello-theme").setTheme("blue");
      });
    </script>
  </body>
</html>
